package com.nervenets.web.controller.handler.admin.user;

import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.RewardInvoice;
import com.nervenets.web.redis.domain.user.UserStored;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UserRewardInvoicesHandler extends SessionHandler<UserRewardInvoicesParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.all();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserRewardInvoicesParams params, HttpServletRequest request) throws Exception {
        String hql = "from RewardInvoice where id > 0 ";
        HashMap<String, Object> objects = new HashMap<>();

        if (null != params.getStatus()) {
            hql += "and status = :status ";
            objects.put("status", params.getStatus());
        }

        final BigDecimal countOfByHql = userDao.getCountOfByHql(hql, objects);
        hql += "order by createTime desc ";
        List<RewardInvoice> results = userDao.getAllObjectsByHql(hql, objects, params.getStart(), params.getLimit());

        HashMap<Long, UserStored> userStoredHashMap = new HashMap<>();
        for (RewardInvoice invoice : results) {
            if (!userStoredHashMap.containsKey(invoice.getUserId())) {
                userStoredHashMap.put(invoice.getUserId(), globalService.getUser(invoice.getUserId()));
            }
        }

        return successMessage(
                results,
                new KeyValue("start", params.getStart()),
                new KeyValue("total", countOfByHql.longValue()),
                new KeyValue("users", userStoredHashMap)
        );
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
